import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../Tracking/tracking-min.js';
import '../Tracking/data/face-min.js';
import '../Tracking/data/eye-min.js';
import '../Tracking/data/mouth-min.js';
import '../Style/demo.css';
import ImageSrc from '../Tracking/assets/faces.jpg';

let imgStyle = {
    position: "absolute",
    top: "50%",
    left: "50%",
    margin: "-173px 0 0 -300px"
  }

class Facial extends Component{
    constructor(props){
        super(props);
    }
    componentDidMount(){
        this.handleLoad();
    }

    handleLoad = () => {
        let { dispatch } = this.props;
        var img = document.getElementById('img');
        img.onload = () => {
            var tracker = new tracking.ObjectTracker(['face', 'eye', 'mouth']);
            tracker.setStepSize(1.7);
            tracking.track('#img', tracker);
            tracker.on('track', (event) => {
                let rectArr = [];
                event.data.forEach((rect) => {
                    rectArr.push({
                        imgOffsetLeft:img.offsetLeft,
                        imgOffsetTop:img.offsetTop,
                        x:rect.x,
                        y:rect.y, 
                        w:rect.width, 
                        h:rect.height});
                });
                dispatch({type:"ADD_RECTS",value:rectArr});
            });
        };
        
        
    }

    render(){
        return(
            <div className="demo-frame">
                <div className="demo-container">
                <img id="img" src={ImageSrc} style={{...imgStyle}} />
                {
                    this.props.rectArr ? this.props.rectArr.map((params,index) => RectCreator(params,index)) : false
                }
                </div>
            </div>
        )
    }
}

const RectCreator = ( params, index ) => {
    let rectStyle = {
        border: "2px solid #a64ceb",
        left: -1000,
        position: "absolute",
        top: -1000
    };
    class Rect extends Component{
        render(){
            let { imgOffsetLeft, imgOffsetTop, x, y, w, h } = this.props.params;
            rectStyle.width = w + 'px';
            rectStyle.height = h + 'px';
            rectStyle.left = (imgOffsetLeft + x) + 'px';
            rectStyle.top = (imgOffsetTop + y) + 'px';
            return(
                <div className="rect" style={{...rectStyle}}>    
                </div>
            )
        }
    }

    return <Rect key={index} params={params} />
}


export default connect(state => state.Facial)(Facial);